package com.example.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.auth.domain.DataNode;
import com.example.auth.domain.User;
import com.example.config.auth.SecurityUtil;
import com.example.config.exception.GlobalExcetion;
import com.example.domain.vo.BusReceiveMsgVo;
import com.example.feign.NodeFeignService;
import com.example.feign.UserFeignService;
import com.example.service.BusSystemReceivemsgService;
import com.example.system.domain.BusSystemReceivemsg;
import com.example.system.domain.BusSystemTableUser;
import com.example.system.service.BusSystemTableUserService;
import com.example.util.Results;
import com.example.util.sql.IdUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("receive")
public class ReceiveMsgController {

    @Value("${spring.application.name}")
    private String appName;

    private static final String SYSTEM_RECEIVE_MSG = "bus_system_receivemsg";

    @Autowired
    private BusSystemTableUserService busSystemTableUserService;

    @Autowired
    private NodeFeignService nodeFeignService;

    @Autowired
    private BusSystemReceivemsgService busSystemReceivemsgService;

    @Autowired
    private UserFeignService userFeignService;

    //接收消息
    @PostMapping("/receivemsg")
    public JSONObject receiveMsg(@RequestBody BusReceiveMsgVo vo) throws GlobalExcetion {
        BusSystemTableUser busSystemTable=busSystemTableUserService.selectByUserId(vo.getToUid(),SYSTEM_RECEIVE_MSG);
        if(busSystemTable!=null){
            DataNode dataNode =nodeFeignService.getDataNodeConfigByServerName(appName);
            BusSystemReceivemsg bus=new BusSystemReceivemsg();
            BeanUtils.copyProperties(vo,bus);
            bus.setUuid(IdUtils.getUUID());
            bus.setCreateTime(new Date());
            bus.setUpdateTime(new Date());
            bus.setToNodeid(dataNode.getId());
            bus.setDsNo(dataNode.getId());
            bus.setIsDeleted(0);
            String saveTable= busSystemTable.getSaveTableName();
            busSystemReceivemsgService.saveBusSystemReceivemsg(saveTable,bus);
            return Results.success("发送成功");
        }
        return Results.error("发送失败");
    }

    @GetMapping("/getmsglist")
    public JSONObject getMsgList() throws GlobalExcetion {
        String userId=SecurityUtil.getUserId();
        BusSystemTableUser tableUser=busSystemTableUserService.selectByUserId(userId,SYSTEM_RECEIVE_MSG);
        String queryTable=tableUser.generateUnionAllTable("to_uid");
        List<BusSystemReceivemsg> list=busSystemReceivemsgService.getList(queryTable,userId);
        JSONArray array=new JSONArray();
        if(list!=null&&list.size()>0){
            for(BusSystemReceivemsg bus:list){
                JSONObject obj=new JSONObject();
                User user=userFeignService.getUserByUserId(bus.getFromUid());
                obj.putAll(JSONObject.parseObject(JSONObject.toJSONString(bus, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue)));
                obj.put("formUser",user.getUsername());
                array.add(obj);
            }
        }
        return Results.success(array);
    }

    @GetMapping("/getmsglist/byformuid")
    public JSONObject getMsgListByFormUid(@RequestParam("formUid")String formUid) throws GlobalExcetion {
        String userId=SecurityUtil.getUserId();
        BusSystemTableUser tableUser=busSystemTableUserService.selectByUserId(userId,SYSTEM_RECEIVE_MSG);
        String queryTable=tableUser.generateUnionAllTable("to_uid");
        List<BusSystemReceivemsg> list=busSystemReceivemsgService.getList(queryTable,userId,formUid);
        JSONArray array=new JSONArray();
        if(list!=null&&list.size()>0){
            for(BusSystemReceivemsg bus:list){
                JSONObject obj=new JSONObject();
                User user=userFeignService.getUserByUserId(bus.getFromUid());
                obj.putAll(JSONObject.parseObject(JSONObject.toJSONString(bus, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue)));
                obj.put("formUser",user.getUsername());
                array.add(obj);
            }
        }
        return Results.success(array);
    }

    @GetMapping("/getmsglistpage")
    public JSONObject getMsgListPage(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                     @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize) throws GlobalExcetion {
        String userId=SecurityUtil.getUserId();
        BusSystemTableUser tableUser=busSystemTableUserService.selectByUserId(userId,SYSTEM_RECEIVE_MSG);
        String queryTable=tableUser.generateUnionAllTable("to_uid");
        IPage<BusSystemReceivemsg> iPage =busSystemReceivemsgService.getPage(new Page(pageNum,pageSize),queryTable,userId);
        JSONArray array=new JSONArray();
        if(iPage.getRecords()!=null&&iPage.getRecords().size()>0){
            for(BusSystemReceivemsg bus:iPage.getRecords()){
                JSONObject obj=new JSONObject();
                User user=userFeignService.getUserByUserId(bus.getFromUid());
                obj.putAll(JSONObject.parseObject(JSONObject.toJSONString(bus, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue)));
                obj.put("formUser",user.getUsername());
                array.add(obj);
            }
        }
        JSONObject obj=new JSONObject();
        obj.put("data",array);
        obj.put("total",iPage.getTotal());
        return Results.success(obj);
    }


    @GetMapping("/getmsglistpage/byformuid")
    public JSONObject getMsgListPage(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                     @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                     @RequestParam("formUid")String formUid) throws GlobalExcetion {
        String userId=SecurityUtil.getUserId();
        BusSystemTableUser tableUser=busSystemTableUserService.selectByUserId(userId,SYSTEM_RECEIVE_MSG);
        String queryTable=tableUser.generateUnionAllTable("to_uid");
        IPage<BusSystemReceivemsg> iPage =busSystemReceivemsgService.getPage(new Page(pageNum,pageSize),queryTable,userId,formUid);
        JSONArray array=new JSONArray();
        if(iPage.getRecords()!=null&&iPage.getRecords().size()>0){
            for(BusSystemReceivemsg bus:iPage.getRecords()){
                JSONObject obj=new JSONObject();
                User user=userFeignService.getUserByUserId(bus.getFromUid());
                obj.putAll(JSONObject.parseObject(JSONObject.toJSONString(bus, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue)));
                obj.put("formUser",user.getUsername());
                array.add(obj);
            }
        }
        JSONObject obj=new JSONObject();
        obj.put("data",array);
        obj.put("total",iPage.getTotal());
        return Results.success(obj);
    }
}
